#include <func.h>
#include "head.h"
int upload(char* argv, int sockFd){
    //puts file
    char arr[100] = "";
    strcpy(arr, argv);
    char* command = strtok(arr, " ");
    char* fileName = strtok(NULL, " ");
    char realName[100] = {0};
    strncpy(realName, fileName, strlen(fileName));
    char realPath[200] = {0};
    sprintf(realPath, "%s%s%s%s%s", ".", "/", PATH, "/", realName);
    // printf("realPath = %s\n", realPath);
    int fd = open(realPath, O_RDWR);
    ERROR_CHECK(fd, -1, "open");
    struct stat statbuf;
    fstat(fd, &statbuf);
    char *p = (char *)mmap(NULL, statbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    unsigned char MD[16];
    MD5((unsigned char*)p, statbuf.st_size, MD);
    char md5[100] = {0};
    char *q = md5;
    for(int i = 0; i < 16; i++){
        sprintf(q, "%02x", MD[i]);
        q += 2;
    }
    // printf("MD5 = %s\n", md5);
    train_t t;
    strcpy(t.buf, md5);
    t.dataLength = strlen(t.buf);
    send(sockFd, &t, sizeof(t.dataLength) + t.dataLength, MSG_NOSIGNAL);//发送MD5码  

    //判断文件是否已存在于服务器
    char isInServer;
    recv(sockFd, &isInServer, 1, MSG_WAITALL);
    if(isInServer == '2'){
        puts("file has been uploaded");
        return 0;
    }

    bzero(&t, sizeof(train_t));
    t.dataLength = sizeof(statbuf.st_size);
    memcpy(&t.buf, &statbuf.st_size, sizeof(statbuf.st_size));
    send(sockFd, &t, sizeof(t.dataLength) + t.dataLength, MSG_NOSIGNAL);//发送文件大小
    //发送文件内容 
    send(sockFd, p, statbuf.st_size, MSG_NOSIGNAL);  
    munmap(p, statbuf.st_size);
    close(fd);
}

